package com.game.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressUtil {
    /**
     * 压缩
     * @param msg
     * @return
     * @throws IOException
     */
    public static byte[] compress(byte[] msg) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        byte[] ret;
        try {
            gzip.write(msg);
            gzip.finish();
            ret = out.toByteArray();
        } finally {
            gzip.close();
            out.close();
        }
        return ret;
    }

    /**
     * 解压
     * @param msg
     * @return
     * @throws IOException
     */
    public static byte[] decompress(byte[] msg) throws IOException {
        ByteArrayInputStream is = new ByteArrayInputStream(msg);
        GZIPInputStream gzip = new GZIPInputStream(is);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] ret;
        try {
            byte[] buf = new byte[1024];
            int num = -1;
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, num);
            }
            ret = out.toByteArray();
            out.flush();
        } finally {
            gzip.close();
            is.close();
            out.close();
        }
        return ret;
    }
}
